package com.yzt.sys.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yzt.base.kit.Base;
import com.yzt.config.websocket.WebSocketService;
import com.yzt.sys.entity.RolePermission;
import com.yzt.sys.service.IRolePermissionService;

/**
 * <p>
 * 角色_权限关联表 前端控制器
 * </p>
 *
 * @author Y
 * @since 2020-12-21
 */
@RestController
@RequestMapping("/sys/rolePermission")
public class RolePermissionController {

	@Autowired
	private IRolePermissionService rolePermissionService;
	@Autowired
	private WebSocketService webSocketService;

	@GetMapping("checked/{roleId}")
	public Base<List<Long>> checked(@PathVariable("roleId") Long roleId) {
		List<Long> list = rolePermissionService.listObjs(Wrappers.<RolePermission>lambdaQuery()
				.select(RolePermission::getPermissionId).eq(RolePermission::getRoleId, roleId), a -> {
					return Long.valueOf(a.toString());
				});
		return Base.okData(list);
	}

	@PostMapping("")
	@Transactional(rollbackFor = Exception.class)
	public Base<Object> save(Long[] permissionIds, Long roleId) throws Exception {
		rolePermissionService.remove(Wrappers.<RolePermission>lambdaQuery().eq(RolePermission::getRoleId, roleId));
		boolean b = true;
		if (permissionIds != null)
			for (Long permissionId : permissionIds) {
				RolePermission rp = new RolePermission();
				rp.setRoleId(roleId);
				rp.setPermissionId(permissionId);
				b = rolePermissionService.save(rp);
				if (!b) {
					throw new Exception("权限分配异常");
				}
			}
		webSocketService.sendMsgToAll(JSON.toJSONString(Base.ok(601, "刷新权限")));
		return Base.ok();
	}
}
